<template>
  <el-drawer v-model="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false"
             :close-on-press-escape="false" size="900px">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef"
             :label-width="$i18n.locale === 'en-US' ? '120px' : '100px'">
      <el-form-item label="题目内容：" prop="question">
        <el-input v-model="dataForm.question" type="textarea" placeholder="请输入题目内容"></el-input>
      </el-form-item>
      <el-form-item label="题目分数：" prop="score">
        <el-input-number v-model="dataForm.score" :disabled="dataForm.questionType===1" :min="1" :max="100"/>
      </el-form-item>
      <el-form-item label="题目类型：" prop="questionType">
        <el-switch v-model="dataForm.questionType" active-text="多选" inactive-text="单选" :active-value="1"
                   :inactive-value="0" @change="switchChange2"/>
      </el-form-item>
      <el-button style="margin-bottom: 14px" type="primary" @click="addANS">添加选项</el-button>
      <el-form-item v-for="(item,index) in dataForm.questionAnswerList" :label="XXArr[index]+'：'" :key="index+'_key'">
        <div style="width: 100%;display: flex;align-items: center">
          <el-input v-model="item.answer" type="textarea" placeholder="请输入答案内容"></el-input>
          <div style="width: 200px;text-align: center">
            <div>是否正确答案</div>
            <el-switch v-model="item.isCorrect" inline-prompt active-text="是" inactive-text="否" :active-value="1"
                       :inactive-value="0" @change="switchChange(index)"/>
          </div>
          <div style="width: 200px;text-align: center" v-show="dataForm.questionType===1">
            <div>题目分数</div>
            <el-input-number size="small" v-model="item.score" :disabled="item.isCorrect===0" :min="item.isCorrect?1:0"
                             :max="item.isCorrect?100:0" @change="inputChange"/>
          </div>
          <div style="width: 120px;text-align: center">
            <el-tooltip
              class="box-item"
              effect="dark"
              content="删除该答案"
              placement="top"
            >
              <el-button type="danger" @click="delectAns(index)" :icon="Delete" circle/>
            </el-tooltip>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle">提交</el-button>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import {reactive, ref} from "vue";
import baseService from "@/service/baseService";
import {useI18n} from "vue-i18n";
import {ElMessage} from "element-plus";
import {Delete} from '@element-plus/icons-vue';
import {useRoute} from "vue-router";

const {query} = useRoute();
let myId = query.id as string;
const {t} = useI18n();
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();
const XXArr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T"];

type answerFace = {
  answer: string,
  score: number,
  isCorrect: number
}

interface myForm {
  bankId: string | undefined,
  id: string,
  question: string,
  score: number,
  questionAnswerList: answerFace[],
  questionType: number
}

const dataForm = reactive<myForm>({
  bankId: myId,
  id: "",
  question: "",
  score: 1,
  questionAnswerList: [],
  questionType: 0 // 题目类型(0:单选 1:多选)
});


const addANS = () => {
  dataForm.questionAnswerList.push({
    answer: "",
    score: 0,
    isCorrect: 0
  })
}

const delectAns = (ind: number) => {
  dataForm.questionAnswerList.splice(ind, 1);
}

const inputChange = () => {
  if (dataForm.questionType === 1) {
    dataForm.score = 0;
    for (let i = 0; i < dataForm.questionAnswerList.length; i++) {
      dataForm.score += dataForm.questionAnswerList[i].score;
    }
  }
}

const switchChange2 = (e: any) => {
  for (let i = 0; i < dataForm.questionAnswerList.length; i++) {
    dataForm.questionAnswerList[i].isCorrect = 0;
  }
  if (e === 1) {
    dataForm.score = 0;
    for (let i = 0; i < dataForm.questionAnswerList.length; i++) {
      dataForm.questionAnswerList[i].score = 0;
      dataForm.score += dataForm.questionAnswerList[i].score;
      console.log(dataForm.questionAnswerList[i].score, "dataForm.questionAnswerList[i].score")
    }
  }
}

const switchChange = (ind: number) => {
  if (dataForm.questionType === 0) {
    for (let i = 0; i < dataForm.questionAnswerList.length; i++) {
      if (i !== ind) {
        dataForm.questionAnswerList[i].isCorrect = 0;
      }
    }
  } else {
    dataForm.questionAnswerList[ind].score = 1;
    for (let i = 0; i < dataForm.questionAnswerList.length; i++) {
      if (dataForm.questionAnswerList[i].isCorrect === 0) {
        dataForm.questionAnswerList[i].score = 0;
      }
    }
    dataForm.score = 0;
    for (let i = 0; i < dataForm.questionAnswerList.length; i++) {
      dataForm.score += dataForm.questionAnswerList[i].score;
    }
  }
}

const rules = ref({
  name: [{required: true, message: t("validate.required"), trigger: "blur"}]
});

const init = (id: number) => {
  visible.value = true;
  dataForm.id = "";
  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }
  if (id) {
    getInfo(id);
  }

};

// 获取信息
const getInfo = (id: number) => {
  baseService.get(`/clc/clcquestion/${id}`).then((res) => {
    Object.assign(dataForm, res.data);
  });
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    if (dataForm.questionAnswerList.length === 0) {
      ElMessage.warning({
        message: "最少要有一个答案",
        duration: 2000
      });
      return
    }
    if (dataForm.questionAnswerList.reduce((prev: any, cur: any) => prev + cur.isCorrect, 0) === 0) {
      ElMessage.warning({
        message: "最少要有一个正确的题目答案",
        duration: 2000
      });
      return
    }
    for (let i = 0; i < dataForm.questionAnswerList.length; i++) {
      if (dataForm.questionType === 1) {
        if (dataForm.questionAnswerList[i].score === 0 && dataForm.questionAnswerList[i].isCorrect === 1) {
          ElMessage.warning({
            message: "题目为多选且答案为正确答案时，分数不能为0",
            duration: 2000
          });
          return
        }
      }
    }
    (!dataForm.id ? baseService.post : baseService.put)("/clc/clcquestion", dataForm).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init
});
</script>
